from typing import Optional
from app.core.crud import CRUDBase
from app.models.camera import CameraConfig
from app.schemas.camera import CameraConfigCreate, CameraConfigUpdate

class CameraConfigController(CRUDBase[CameraConfig, CameraConfigCreate, CameraConfigUpdate]):
    def __init__(self):
        super().__init__(model=CameraConfig)

    async def get_by_camera_type(self, camera_type: str) -> Optional[CameraConfig]:
        """根据相机类型获取配置"""
        return await self.model.filter(camera_type=camera_type).first()

    async def create_or_update(self, obj_in: CameraConfigCreate) -> CameraConfig:
        """创建或更新相机配置"""
        camera_config = await self.get_by_camera_type(obj_in.camera_type)
        if camera_config:
            return await self.update(id=camera_config.id, obj_in=obj_in)
        return await self.create(obj_in=obj_in)

    def get_camera_config_sync(self, camera_type: str):
        """同步方式获取相机配置"""
        from tortoise import Tortoise, run_async
        
        async def _get_config():
            if not Tortoise._connections:
                await Tortoise.init(
                    db_url="sqlite://db.sqlite3",  # 使用实际的数据库配置
                    modules={"models": ["app.models"]}
                )
            return await self.get_by_camera_type(camera_type)
        
        return run_async(_get_config())

camera_config_controller = CameraConfigController() 